#include <grpc/grpc.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>

#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <memory>
#include <string>
#include <stdlib.h> 
#include <string.h>
#include <unistd.h>
#include <time.h> 

#include "data.grpc.pb.h"
#include "data.pb.h"

using namespace grpc;
using namespace std;
#define randof(num)  (int) ((float) (num) * random () / (RAND_MAX + 1.0))

class AgvService final : public GrpcService::Service {
 public:
  explicit AgvService() { cout << "new obj..." << endl; }

  virtual Status StopReport(ServerContext* context, const InputAction* request,
                            ErrorMessage* response) {
    response->set_errcode(0);
    response->set_errmsg("OK");
    return Status::OK;
  }
  virtual Status StartReport(ServerContext* context, const InputAction* request,
                             ServerWriter<DeviceProperty>* writer) {
    int i = 0;
    while (1) {
      DeviceProperty response;
      response.set_version("0.0.1");
      PropertyInfo* info = response.add_attrinfo();
      info->set_attrname("VehicleInfo");
      VehicleInfo vi;
      vi.set_battery(randof(100));
      info->set_attrvalue(vi.SerializeAsString());

      info = response.add_attrinfo();
      info->set_attrname("MotionInfo");
      MotionInfo mi;
      mi.set_velocity(randof(100));
      info->set_attrvalue(mi.SerializeAsString());

      // response.set_message(++i + request->name());
      writer->Write(response);
      sleep(1);
    }
    return Status::OK;
  }
};

void RunServer() {
  std::string server_address("0.0.0.0:50051");
  AgvService service;

  ServerBuilder builder;
  builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  builder.RegisterService(&service);
  std::unique_ptr<Server> server(builder.BuildAndStart());
  std::cout << "Server listening on " << server_address << std::endl;
  server->Wait();
}

int main(int argc, char** argv) {
  RunServer();

  return 0;
}
